package org.spbsu.apco.common.utils;

import org.perf4j.StopWatch;
import org.perf4j.slf4j.Slf4JStopWatch;
import org.spbsu.apco.common.properties.ApplicationPropertiesManager;
import org.spbsu.apco.common.properties.PropertyKey;

/**
 * User: ortemij
 * Date: 11.01.13
 * Time: 19:29
 */
public class StopWatchFactory {

    private static EmptyStopWatch emptyStopWatch = new EmptyStopWatch();
    private static ThreadLocalStopWatch threadLocalStopWatch = new ThreadLocalStopWatch();

    private StopWatchFactory() {
    }

    public static StopWatch create() {
        final String mode = ApplicationPropertiesManager.getProperty(PropertyKey.STOPWATCH_FACTORY_MODE);
        if (mode != null && mode.equals("production")) {
            return emptyStopWatch;
        }
        return new Slf4JStopWatch();
    }

    public static StopWatch createOrGetLocal() {
        return threadLocalStopWatch.get();
    }

    private static class ThreadLocalStopWatch extends ThreadLocal<StopWatch> {
        @Override
        public StopWatch initialValue() {
            return create();
        }
    }

    private static class EmptyStopWatch extends StopWatch {
        @Override
        public void start() {
        }

        @Override
        public void start(String tag) {
        }

        @Override
        public void start(String tag, String message) {
        }

        @Override
        public String stop() {
            return "";
        }

        @Override
        public String stop(String tag) {
            return "";
        }

        @Override
        public String stop(String tag, String message) {
            return "";
        }

        @Override
        public String lap(String tag) {
            return "";
        }

        @Override
        public String lap(String tag, String message) {
            return "";
        }
    }
}
